const express = require("express");
var exphbs = require('express-handlebars')
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const app = express();

/*连接数据库*/
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://lzc:lzc0401@59.110.136.247/node-app")
		.then(() => {
			console.log('成功')
		})
		.catch(err => {
			console.log('失败')
		})
/*var opts = {
	user: 'lzc',
	pass: 'LIUzc0401',
	server: {
		auto_reconnect: true,
		poolSize: 10
	}
};
mongoose.connect('59.110.136.247', 'node-app', 27017, opts);*/
require("./models/Idea")

const Idea = mongoose.model('ideas');

// body-parser middleware
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.engine('handlebars', exphbs({
	defaultLayout: 'main'
}))
app.set('view engine', 'handlebars')

// 配置路由
app.get("/",(req,res) => {
  const title = "大家好,我是米斯特吴!!!!";
  res.render("index",{
    title:title
  });
})

app.get("/about",(req,res) => {
  res.render("about");
})

app.get("/ideas/add",(req,res) => {
  res.render("ideas/add");
})

app.post("/ideas", urlencodedParser, (req,res) => {
	/*var params = req.body
	console.log(params)
	if (!params.title || !params.details) {
		res.send('参数错误111');
		return;
	}*/
	
	const newUser = {
		title: "aaa",
		details: "bbb"
	}
	console.log(newUser)
	//res.send(newUser);
	new Idea(newUser)
		.save()
		/*.then(idea => {
			res.send('ok')
		})*/
})

const port = 5001;

app.listen(port, () => {
	console.log(`Server start on ${port}`);
})
